package  com.htjc.integral.account.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.account.entity.Response;
import com.htjc.integral.account.mapper.uep.CenterApplyMapper;
import com.htjc.integral.account.mapper.uep.ExtendedMapper;
import com.htjc.integral.account.service.ICenterService;
import com.htjc.uep.center.commons.bean.BeanContext;
import com.htjc.uep.center.commons.utils.DateUtil;
import com.htjc.uep.center.commons.utils.JsonUtil;
import com.htjc.uep.center.commons.utils.KeyUtil;
import com.htjc.uep.center.commons.utils.RequestUtil;
import com.htjc.uep.center.commons.utils.SignUtil;
import com.htjc.uep.center.commons.utils.UUIDUtil;
import com.htjc.uep.center.model.entity.SaExtendedConfig;
import com.htjc.uep.center.model.entity.UpPool;
import com.htjc.uep.center.model.enums.AddIntegralStatus;
import com.htjc.uep.center.model.enums.BusinessType;
import com.htjc.uep.center.model.enums.ConsumeStatus;
import com.htjc.uep.center.model.enums.DeductionStatus;
import com.htjc.uep.center.model.enums.ErrorStatus;
import com.htjc.uep.center.model.enums.ExtendedConstant;
import com.htjc.uep.center.model.enums.GWAddIntegralStatus;
import com.htjc.uep.center.model.enums.GWChannelNo;
import com.htjc.uep.center.model.enums.GWOperationType;
import com.htjc.uep.center.model.enums.GWPlatformType;
import com.htjc.uep.center.model.enums.OperationType;
import com.htjc.uep.center.model.enums.PlatformStatus;
import com.htjc.uep.center.model.enums.PlatformType;
import com.htjc.uep.center.model.service.request.AddPointResquest;
import com.htjc.uep.center.model.service.request.DeductionPointsRequest;
import com.htjc.uep.center.model.service.request.GWAddPointResquest;
import com.htjc.uep.center.model.service.request.QueryAccountCodeRequest;
import com.htjc.uep.center.model.service.request.QueryPoolRequest;
import com.htjc.uep.center.model.service.response.BasicDeductionResponse;
import com.htjc.uep.center.model.service.response.DeductionPointResponse;
import com.htjc.uep.center.model.service.response.QueryPoolResponse;

@Service
@Repository
public class CenterServiceImpl implements ICenterService{

	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private CenterApplyMapper applyMapper;
	
	@Autowired
	private ExtendedMapper extendedMapper;
	
	@Override
	public String deductionPointsApply(DeductionPointsRequest applyRequest) {
		log.info("积分中心业务服务-当前业务类型={}开始", BusinessType.APPLY_DEDUCTION_POINT.getType());
		
		//该合作平台下是否有积分池
		if(!applyMapper.queryPoolIsEmpty(applyRequest.getMechanismCode(), applyRequest.getAccountCode())) {
			log.info("====>>>>积分扣减业务异常<<<<====积分池不存在或已冻结,合作平台编号={}", applyRequest.getMechanismCode());
			
			//是否存在合作平台，如没有则返回异常
			if (!applyMapper.queryPlatformIsEmpty(applyRequest.getMechanismCode(), PlatformStatus.PLATFORM_STATUS_01.getCode())) {
				log.info("====>>>>积分扣减业务异常<<<<====合作平台不存在或已冻结,合作平台编号={}", applyRequest.getMechanismCode());
				return JsonUtil.getError(ErrorStatus.ERROR_PALTFORM_NULL);
			}
			return JsonUtil.getError(ErrorStatus.ERROR_POOL_NULL);
		}
		//积分扣减明细表插入数据，状态为扣减中
		String flowId = UUIDUtil.getUUID32();
		log.info("====>>>>积分扣减业务<<<<====在积分扣减明细表中插入数据,明细ID={},扣减状态={}", flowId, ConsumeStatus.CONSUME_STATUS_01.getCode());
		
		applyMapper.insertPoolConsume(applyRequest, flowId, ConsumeStatus.CONSUME_STATUS_01.getCode(), applyRequest.getDealId());
		
		String result = "";
		
		try {
			ExtendedConstant extended = ExtendedConstant.EXTENDED_TYPE;
			SaExtendedConfig configAddPool = extendedMapper.queryConfigByTypeId(extended.getCode(), extended.getType(), extended.getTypeId());

			String url = configAddPool.getEXT_TYPE_VALUE();
//			log.info("====>>>>积分扣减业务<<<<====得到积分扣减基础服务接口地址");
			
//			BasicDeductionResponse basicDeductionResponse = new BasicDeductionResponse();
//			basicDeductionResponse.setAccountCode(applyRequest.getAccountCode());
//			basicDeductionResponse.setDealId(applyRequest.getDealId());
//			basicDeductionResponse.setMechanismCode(applyRequest.getMechanismCode());
//			basicDeductionResponse.setScore(new BigDecimal(applyRequest.getScore()));
//			
//			String param = JSONObject.toJSONString(basicDeductionResponse);
////			KeyUtil keyUtil = BeanContext.getBean(KeyUtil.class);
////			String paramKey = keyUtil.encryptByPublic(param);
//			
//			log.info("====>>>>积分扣减业务<<<<====调用基础服务，积分扣减服务");
//			log.info("====>>>>积分扣减业务<<<<====基础服务积分扣减业务请求报文={}",param);
//			result = RequestUtil.sendPost(url, param);
			
			log.info("====>>>>积分池扣减业务开始<<<<====");
			UpPool upPool = applyMapper.queryUpPoolTMP(applyRequest.getMechanismCode(), applyRequest.getAccountCode(), "01");
			applyMapper.consumePool(upPool.getPOOL_ID(),new BigDecimal(applyRequest.getScore()) );
			log.info("====>>>>积分池扣减业务完成<<<<====");
			
//			JSONObject resultJson = JSONObject.parseObject(result);
//			if (resultJson.getInteger("code") != 1) {
//				log.info("====>>>>积分扣减业务<<<<====基础服务积分扣减业务失败,明细ID={},扣减状态为={}", flowId, ConsumeStatus.CONSUME_STATUS_03.getCode());
//				applyMapper.updatePoolConsume(flowId, ConsumeStatus.CONSUME_STATUS_03.getCode());
//				return result;
//			}
			log.info("====>>>>积分扣减业务<<<<====基础服务积分扣减业务成功");
			//调用积分增加接口，并得出结果
			log.info("====>>>>积分扣减业务<<<<====积分账户余额增加服务");
			String platformType = "";
			if (PlatformType.PLATFORM_TYPE_7110101.getCode().equals(applyRequest.getMechanismCode()) || PlatformType.PLATFORM_TYPE_7110102.getCode().equals(applyRequest.getMechanismCode())) {
				platformType = "01";
			} else {
				platformType = "02";
			}
			String repsonse = "";
			
			AddPointResquest addPointRequest = new AddPointResquest();
			
			addPointRequest.setACCOUNT_NAME(applyRequest.getPhone());	
			addPointRequest.setACCOUNT_ID(applyRequest.getUserId());	
			addPointRequest.setBUSINESS_ID(flowId);	
			addPointRequest.setCHANNEL_NO(applyRequest.getChannel());
			addPointRequest.setBUSS_TYPE(platformType);
			addPointRequest.setOPERATION_TYPE(OperationType.OPERATION_TYPE_01.getCode());
			
			if (PlatformType.PLATFORM_TYPE_33101.equals(applyRequest.getMechanismCode())) {
				addPointRequest.setBUSS_DISCRIBLE(PlatformType.PLATFORM_TYPE_33101.getType() + "加" + applyRequest.getScore() + "积分");	
			} else if (PlatformType.PLATFORM_TYPE_7110101.equals(applyRequest.getMechanismCode())) {
				addPointRequest.setBUSS_DISCRIBLE(PlatformType.PLATFORM_TYPE_7110101.getType() + "加" + applyRequest.getScore() + "积分");	
			} else if (PlatformType.PLATFORM_TYPE_7110102.equals(applyRequest.getMechanismCode())) {
				addPointRequest.setBUSS_DISCRIBLE(PlatformType.PLATFORM_TYPE_7110102.getType() + "加" + applyRequest.getScore() + "积分");	
			} else {
				addPointRequest.setBUSS_DISCRIBLE("网省渠道,加" + applyRequest.getScore() + "积分");	
			}
			
			addPointRequest.setINTEGRAL(new BigDecimal(applyRequest.getScore()));
			addPointRequest.setDEAL_TIME(DateUtil.formatDate(DateUtil.parseDate(applyRequest.getSendTime(), DateUtil.DATE_YYYY_MM_DD_HH_MM_SS).getTime(), DateUtil.DATE_YYYYMMDDHHMMSS));	
			
			SimpleDateFormat dataFormat2 = new SimpleDateFormat("yyyyMMdd");
			String createTime = dataFormat2.format(new Timestamp(System.currentTimeMillis()));
			
			addPointRequest.setCREATE_DATE(createTime);	
			addPointRequest.setACCT_DATE(applyRequest.getAcctDate());

			String AddPointsParam = JSONObject.toJSONString(addPointRequest);
			
			log.info("====>>>>积分扣减业务<<<<====积分账户余额增加服务请求报文={}", AddPointsParam);
			
			ExtendedConstant extendedInner = ExtendedConstant.EXTENDED_POINTS_ADD;
			SaExtendedConfig pointsAddConfig = extendedMapper.queryConfigByTypeId(extendedInner.getCode(), extendedInner.getType(), extendedInner.getTypeId());

			repsonse = RequestUtil.sendPost(pointsAddConfig.getEXT_TYPE_VALUE(), AddPointsParam);
			
			if (repsonse == null || "".equals(repsonse)) {
				log.info("====>>>>积分扣减业务<<<<====积分账户余额增加服务失败,响应报文={}", repsonse);
				//异常更新积分扣减明细表
				applyMapper.updatePoolConsume(flowId, ConsumeStatus.CONSUME_STATUS_03.getCode());
				return JsonUtil.getError(ErrorStatus.ERROR_DEDUCTION_ADD);
			}
			JSONObject resultJsonPoints = JSONObject.parseObject(repsonse);
			
			log.info("====>>>>积分扣减业务<<<<====积分账户余额增加服务,响应报文={}", repsonse);
			
			if (!AddIntegralStatus.ADD_INTEGRAL_STATUS_1.getCode().equals(resultJsonPoints.getJSONObject("content").getString("STATUS"))) {
				log.info("====>>>>积分扣减业务<<<<====积分账户余额增加服务失败");
				//异常更新积分扣减明细表
				applyMapper.updatePoolConsume(flowId, ConsumeStatus.CONSUME_STATUS_03.getCode());
				return repsonse;
			}
			//签名
			SignUtil signUtil = SignUtil.getInstance();
			
			String balance = signUtil.aesEncrypt(resultJsonPoints.getJSONObject("content").getString("BALANCE"));
			String dealId = signUtil.aesEncrypt(applyRequest.getDealId());
			String handleId = signUtil.aesEncrypt(flowId);
			String mechanismCode = signUtil.aesEncrypt(applyRequest.getMechanismCode());
			String accountCode = signUtil.aesEncrypt(applyRequest.getAccountCode());
			String status = signUtil.aesEncrypt(DeductionStatus.DEDUCTION_TYPE_01.getCode());
			String sendTimeResponse = signUtil.aesEncrypt(DateUtil.formatDate(new Timestamp(System.currentTimeMillis()).getTime(), DateUtil.DATE_YYYY_MM_DD_HH_MM_SS));
			
			DeductionPointResponse dedPointResponse = new DeductionPointResponse();
			dedPointResponse.setBalance(balance);
			dedPointResponse.setDealId(dealId);
			dedPointResponse.setHandleId(handleId);
			dedPointResponse.setMechanismCode(mechanismCode);
			dedPointResponse.setAccountCode(accountCode);
			dedPointResponse.setStatus(status);
			dedPointResponse.setSendTime(sendTimeResponse);
			
			//签名参数
			String signParam = dealId + handleId + mechanismCode + accountCode + status + sendTimeResponse;
			//签名结果
			String sign = signUtil.sign(signParam);
			//成功，更新积分扣减明细表
			applyMapper.updatePoolConsume(flowId, ConsumeStatus.CONSUME_STATUS_02.getCode());
			log.info("====>>>>积分扣减业务<<<<====积分扣减业务成功,明细ID={},扣减状态为={}", flowId, ConsumeStatus.CONSUME_STATUS_02.getCode());
			return JsonUtil.getSuccessSign(sign, dedPointResponse);
		} catch (Exception e) {
			log.error("====>>>>积分扣减业务异常<<<<====积分池扣减接口调用异常,合作平台编号={}", applyRequest.getMechanismCode(), e);
			//异常更新积分扣减明细表
			applyMapper.updatePoolConsume(flowId, ConsumeStatus.CONSUME_STATUS_03.getCode());
			return JsonUtil.getError(ErrorStatus.ERROR_DEDUCTION_EXCEPT);
		}
	}

	@Override
	//积分池查询接口
	public String queryPoolApply(QueryPoolRequest applyRequest) throws Exception {
		log.info("积分中心-业务服务-当前业务类型={}开始", BusinessType.APPLY_QUERY_POOL.getType());
		
		//该合作平台下是否有积分池
		if(!applyMapper.queryPoolIsEmpty(applyRequest.getMechanismCode(), applyRequest.getAccountCode())) {
			log.info("====>>>>积分池查询业务异常<<<<====积分池不存在或已冻结,合作平台编号={}", applyRequest.getMechanismCode());
			
			//是否存在合作平台，如没有则返回异常
			if (!applyMapper.queryPlatformIsEmpty(applyRequest.getMechanismCode(), PlatformStatus.PLATFORM_STATUS_01.getCode())) {
				log.info("====>>>>积分池查询业务异常<<<<====合作平台不存在或已冻结,合作平台编号={}", applyRequest.getMechanismCode());
				return JsonUtil.getError(ErrorStatus.ERROR_PALTFORM_NULL);
			}
			return JsonUtil.getError(ErrorStatus.ERROR_POOL_NULL);
		}
		UpPool upPool = applyMapper.queryUpPool(applyRequest.getMechanismCode(), applyRequest.getAccountCode());

		SignUtil signUtil = SignUtil.getInstance();
		
		String repertoryName = signUtil.aesEncrypt(upPool.getPOOL_NO());
		String accountCode = signUtil.aesEncrypt(applyRequest.getAccountCode());
		String mechanismCode = signUtil.aesEncrypt(applyRequest.getMechanismCode());
		String bpValue = signUtil.aesEncrypt(String.valueOf(upPool.getBALANCE()));
		String status = signUtil.aesEncrypt(upPool.getPOOL_STATUS());
		String createTime = signUtil.aesEncrypt(DateUtil.formatDate(upPool.getCREATE_TIME().getTime(), "yyyy-MM-dd HH:mm:ss"));
		String updateTime = signUtil.aesEncrypt(DateUtil.formatDate(upPool.getUPDATE_TIME().getTime(), "yyyy-MM-dd HH:mm:ss"));
		
		//生成响应报文		
		QueryPoolResponse queryPoolResponse = new QueryPoolResponse();
		queryPoolResponse.setRepertoryName(repertoryName);
		queryPoolResponse.setAccountCode(accountCode);
		queryPoolResponse.setMechanismCode(mechanismCode);
		queryPoolResponse.setBpValue(bpValue);
		queryPoolResponse.setStatus(status);
		queryPoolResponse.setCreatedTime(createTime);
		queryPoolResponse.setLastUpdateTime(updateTime);
		//签名
		String param = repertoryName + accountCode + mechanismCode + bpValue + status + createTime + updateTime;
		String sign = signUtil.sign(param);
		log.info("====>>>>积分池查询业务<<<<====积分池查询业务成功");
		return JsonUtil.getSuccessSign(sign, queryPoolResponse);		
	}
	
	@Override
	public String queryAccountCode(QueryAccountCodeRequest accountRequest) throws Exception {
//		Response response = new Response();
//		SignUtil signUtil = SignUtil.getInstance();
//		if (!applyMapper.queryPoolIsEmpty(accountRequest.getMechanismCode(), accountRequest.getAccountCode())){
//			log.info("合作平台或结算编码校验异常");
//			String returnCode = signUtil.aesEncrypt("02");
//			String returnMessage = signUtil.aesEncrypt("该结算单位不存在或已冻结"); 
//			
//			response.setReturnCode(returnCode);
//			response.setReturnMessage(returnMessage);
//			
//			return JsonUtil.getError(response);
//		}
//		String returnCode = signUtil.aesEncrypt("01");
//		String returnMessage = signUtil.aesEncrypt("运行中"); 
//		
//		response.setReturnCode(returnCode);
//		response.setReturnMessage(returnMessage);
//		
//		String param = returnCode + returnMessage; 
//		String sign = signUtil.sign(param);
//		
//		return JsonUtil.getSuccessSign(sign, response);
		////////////////////////非签名验签/////////////////////////////////
		Response response = new Response();
		SignUtil signUtil = SignUtil.getInstance();
		if (!applyMapper.queryPoolIsEmpty(accountRequest.getMechanismCode(), accountRequest.getAccountCode())){
			log.info("合作平台或结算编码校验异常");
			String returnCode = "02";
			String returnMessage = "该结算单位不存在或已冻结"; 
			
			response.setReturnCode(returnCode);
			response.setReturnMessage(returnMessage);
			
			return JsonUtil.getError(response);
		}
		String returnCode = "01";
		String returnMessage = "运行中"; 
		
		response.setReturnCode(returnCode);
		response.setReturnMessage(returnMessage);
		
		String param = returnCode + returnMessage; 
		String sign = signUtil.sign(param);
		
		return JsonUtil.getSuccessSign(sign, response);
	}
}